#!/usr/bin/env python
#coding=utf-8
import yyWeb
import parse
import threading
import wx


class LoginThread(threading.Thread):  
    def __init__(self, window, name, pwd):
        threading.Thread.__init__(self)
        self.window = window
        self.name = name
        self.pwd = pwd
        
    #login############################
    def uLogin(self):
        mainPage = self.login()
        if mainPage:
            if mainPage['error']:
                wx.CallAfter(self.window.messageCall, u'[%s]，请确认要登录的用户名和密码' % mainPage['error'])
                return False
            else:
                if mainPage.has_key('renqi'):
                    wx.CallAfter(self.window.messageCall, u'基本信息：%s' % mainPage)
                    return True
                else:
                    wx.CallAfter(self.window.messageCall, u'[%s]可能已经被挂起，请登录页面查看' % self.name)
                    return False
        else:
            wx.CallAfter(self.window.messageCall, u'登录失败，请重新开始')
            return False
    
    def login(self):
        wx.CallAfter(self.window.messageCall, u'%s正在登录...' % self.name)
        self.web = yyWeb.YYWeb(logfile='', interval_time=2)
        f = self.web.login(self.name, self.pwd)
        mainPage = parse.parseMain(f)
        return mainPage
        
    def getRegisterCode(self):
        f = self.web.invitelist()        
        inviteUrl = parse.parseInviteList(f)
        if inviteUrl:
            wx.CallAfter(self.window.messageCall, u'获取邀请地址成功')
        else:
            wx.CallAfter(self.window.messageCall, u'获取邀请地址失败') 
        return inviteUrl    
    
    #main################################            
    def run(self): 
        if self.uLogin():
            inviteUrl = self.getRegisterCode()
            wx.CallAfter(self.window.successCall, inviteUrl)
            
